define(window.backboneCommon.getViewDefine("user.detail"), function ($,require,Collection,tpl) {
    var defaultsOptions={
        submitCallback:null
    };
    var pagePrivate = {
        getDefaults :function () {
            return defaultsOptions
        },
        getOptions : function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            return $.ExtCommon.initMergeJson(this.getDefaults(),options);
        }
    };
    var backboneView= Backbone.View.extend({
        events: {
            "click #btn_PasswordCancel": "passwordCancel",
            "click #btn_PasswordEdit": "passwordEdit",
            "click #btn_SubmitUserDetail": "saveSubmit"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.customer=this.model.get("modelCustomer");
            this.modelAttach.agent=this.model.get("modelAgent");
            this.listenTo(this.modelAttach.customer, 'bind:AllList', this.bindCustomer);
            this.listenTo(this.modelAttach.agent, 'bind:AllList', this.bindAgent);
            this.listenTo(this.model, 'bind:Info', this.bindInfo);
            this.listenTo(this.model, 'save:Info', this.saveInfoCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(options){
            this.elementModel={};
            this.extObject={};
            this.pageData={initPage:false};
            this.pageOptions=$.ExtCommon.initMergeJson(pagePrivate.getOptions(),options);
            this.elementModel.form=$("#form_detail");
            this.pageData.listStatus=this.model.get("defListStatus");
            this.pageData.listRole={};
            this._initPagePower();
        },
        initPage:function (json) {
            this.bindInfo(json)
        },
        _initPagePower:function(){
            var self=this;
            $.ExtAssist.rolePower.operatePage("create|edit",["advertiser"],function(json){
                self.pageData.power={
                    isAdvertiser:json["advertiser"]
                };
                self._initBodyMain();
            });
        },
        _initBodyMain:function(){
            this._bindStatus();
            this._bindUserRole();
            this.elementModel.form.ExtParsley();
        },
        _bindStatus:function () {
            this.extObject.status=$("#panel_status").ExtRadioCheckbox({type: "radio",attrName:"status",defaultInfo:{width:75},
                data:this.pageData.listStatus
            });
        },
        _bindUserRole:function () {
            var self=this;
            self.pageData.listRole=self.pageData.power.isAdvertiser?self.model.get("defAdvertiserListRole"):self.model.get("defAgentListRole");
            self.extObject.useRrole=$("#panel_userrole").ExtRadioCheckbox({type: "radio",attrName:"userRole",defaultInfo:{width:75},
                data:this.pageData.listRole,
                changeCallback:function (value) {
                    self._changeUserRole(value);
                }
            });
        },
        _changeUserRole:function(value){
            var pEl=$("#panel_actor");
            if(this.pageData.power.isAdvertiser){
                switch(value){
                    case "agent":
                        pEl.hide();
                        $("#ddl_actorId").removeAttr("required");
                        break;
                    case "advertiser":
                        pEl.show();
                        $("#ddl_actorId").attr("required","");
                        break;
                }
            }else{
                 pEl.show();
                 $("#ddl_actorId").attr("required","");
            }
        },
        bindCustomer:function () {
            var self=this;
            var res=this.modelAttach.customer.get("dataAllList");
            var list=$.ExtCommon.convertListByPara(res.data,{name:"nameExt"});
            self.extObject.customer=$("#ddl_actorId").ExtSelect2({placeholder: "-广告主-",allowClear: true,minimumResultsForSearch: 1,infoExt:{data:list,
                initCallback:function(){
                    self.pageData.userInfo.isAdd?self.extObject.customer.removeDisabled():self.extObject.customer.disabled();
                },
                changeCallback: function (value, element) {
                    self.elementModel.form.ExtParsley().validate(element)
                }
            }});
        },
        bindAgent:function () {
            var self=this;
            var res=this.modelAttach.agent.get("dataAllList");
            var list=$.ExtCommon.convertListByPara(res.data,{name:"nameExt"});
            self.extObject.customer=$("#ddl_actorId").ExtSelect2({placeholder: "-代理商-",allowClear: true,minimumResultsForSearch: 1,infoExt:{data:list,
                initCallback:function(){
                    self.pageData.userInfo.isAdd?self.extObject.customer.removeDisabled():self.extObject.customer.disabled();
                },
                changeCallback: function (value, element) {
                    self.elementModel.form.ExtParsley().validate(element)
                }
            }});
        },
        bindInfo:function (json) {
            var self=this;
            $("#modal_detail").find(".modal-title").text(json.isAdd?"新建用户":"编辑用户");
            self.extObject.form=self.elementModel.form.ExtFormValue({isRunBind:false,
                initCallback: function (datajson) {
                    self.pageData.userInfo=datajson;
                    if(!self.pageData.initPage) {
                        self.pageData.initPage = true;
                        if(self.pageData.power.isAdvertiser){
                            self.collection.getCustomer();
                        }else{
                            self.collection.getAgent();
                        }
                    }
                    $("#txt_name").prop("disabled", !datajson.isAdd);
                    $(".panel-user-add").toggle(datajson.isAdd);
                    $(".panel-user-edit").toggle(!datajson.isAdd);
                    if(datajson.isAdd){
                        $(".panel-user-add input").attr("required","");
                        $(".panel-user-edit input").removeAttr("required");
                        self.extObject.useRrole.cleanDisabledAll();
                    }else{
                        $(".panel-user-add input").removeAttr("required");
                        $("#txt_PasswordEidt").val("").removeAttr("required").parent().hide();
                        $("#btn_PasswordEdit").parent().show();
                        self.extObject.useRrole.disabledAll();
                    }
                    if(self.extObject.customer){
                        datajson.isAdd?self.extObject.customer.removeDisabled():self.extObject.customer.disabled();
                    }
                    self.extObject.status.setValue(datajson.status.toString());
                    self.extObject.useRrole.setValue(datajson.userRole);
                    self.elementModel.form.ExtParsley("reset");
                    self._modalShow();
                }
            });
            self.extObject.form.cleanValue();
            self.extObject.form.bindValueData(json);
        },
        passwordEdit:function (e) {
            $(e.currentTarget).val();
            $(e.currentTarget).parent().hide().next().show().find(".box-input").attr("required","").val();
        },
        passwordCancel:function (e) {
            $(e.currentTarget).prevAll(".box-input").val("").removeAttr("required").parent().hide().prev().show();
        },
        _modalShow:function () {
            $("#modal_detail").modal("show");
            $.ExtAssist.modal.computeTop("#modal_detail");
        },
        _modalHide:function () {
            $("#modal_detail").modal("hide")
        },
        _checkFrom:function () {
            return this.elementModel.form.ExtParsley("validate");
        },
        saveSubmit:function(){
            if (this._checkFrom()) {
                var infoOriginal = this.elementModel.form.ExtFormValue("getOriginalData");
                var ajaxData = this.elementModel.form.ExtFormValue("getValues");
                if (infoOriginal.id) {ajaxData.id = infoOriginal.id}
                this.collection.saveInfo(ajaxData);
                this._modalHide();
            }
        },
        saveInfoCallback: function () {
            var self=this;
            var result=this.model.get("dataSave");
            if (result.res.success) {
                $.ExtNotify.success("保存成功!");
                if(this.pageOptions.submitCallback){this.pageOptions.submitCallback(result.isAdd,result.req)}
            }else{
                self._modalShow();
                $.ExtNotify.error(result.res.msg);
            }
        }
    });
    var viewModel=function(options){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el:options.pElement,collection:this.collection,model:this.model});
        this.view.initMain(options);
    };
    viewModel.prototype={
        init:function (json) {
            this.view.initPage(json);
        }
    };
    return viewModel;
});